package cn.xyh.controller;


import cn.xyh.constant.Constant;
import cn.xyh.constant.SysUtil;
import cn.xyh.exception.UserException;
import cn.xyh.model.User;
import cn.xyh.service.IUserService;
import cn.xyh.util.MD5Util;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserService userServiceImpl;

    /**
     * 新增
     */
    @RequestMapping("/insertUser")
    public ModelAndView insertUser(HttpServletRequest request, HttpServletResponse response, @ModelAttribute User entity) {
        ModelAndView mv = null;
        try {
            userServiceImpl.insertUser(entity);
            mv = new ModelAndView("payoff");
        } catch (UserException e) {
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * 登录
     */
    @RequestMapping("/login.json")
    @ResponseBody
    public void Login(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter pw = null;
        Map map = new HashMap();
        try {
            pw = response.getWriter();
            User currentUser = (User) request.getSession().getAttribute(Constant.LoginSessionUser);
            String loginName = request.getParameter("username");
            String password = request.getParameter("password");
            String code = request.getParameter("code");
            String rememberMe = request.getParameter("type");
            String piccode = (String) request.getSession().getAttribute("piccode");
            if (!SysUtil.isNull(piccode))
                piccode = piccode.toLowerCase();
            if (SysUtil.isNull(currentUser)) {

                if (SysUtil.isNull(loginName)) {
                    map.put("status", 400);
                    map.put("msg", Constant.NOT_PARAMER);
                    pw.print(JSON.toJSONString(map).toString());
                } else if (SysUtil.isNull(password)) {
                    map.put("status", 400);
                    map.put("msg", Constant.NOT_PARAMER);
                    pw.print(JSON.toJSONString(map).toString());
                } else if (code.trim().equals("验证码:")) {
                    map.put("status", 400);
                    map.put("msg", Constant.CODE);
                    pw.print(JSON.toJSONString(map).toString());
                } else if (!code.trim().equals(piccode)) {
                    map.put("status", 400);
                    map.put("msg", Constant.CODE_FAILE);
                    pw.print(JSON.toJSONString(map).toString());
                } else {
                    User vo = new User();
                    vo.setLoginName(loginName.trim());
                    vo.setPassword(MD5Util.md5encode(password.trim()));
                    Integer c = userServiceImpl.getUserCount(vo);
                    if (c > 0) {
                        UsernamePasswordToken token = new UsernamePasswordToken(loginName, MD5Util.md5encode(password));
                        Subject shiroUser = SecurityUtils.getSubject();
                        if (!shiroUser.isAuthenticated()) {
                            //使用shiro来验证
                            if (rememberMe.equals("1")) {
                                token.setRememberMe(true);
                            } else {
                                token.setRememberMe(false);
                            }
                            shiroUser.login(token);//验证角色和权限

                        }
                        request.getSession().setAttribute(Constant.LoginSessionUser, vo);
                        request.getSession().setMaxInactiveInterval(1 * 60 * 60);
                        map.put("status", 200);
                        map.put("msg", Constant.LOGIN_SUCCESS);
                        pw.print(JSON.toJSONString(map).toString());
                    } else {
                        map.put("status", 400);
                        map.put("msg", Constant.USER_PASSWORD);
                        pw.print(JSON.toJSONString(map).toString());
                    }
                }
            } else {
                if (SysUtil.isNull(loginName)) {
                    map.put("status", 400);
                    map.put("msg", Constant.NOT_PARAMER);
                    pw.print(JSON.toJSONString(map).toString());
                } else if (SysUtil.isNull(password)) {
                    map.put("status", 400);
                    map.put("msg", Constant.NOT_PARAMER);
                    pw.print(JSON.toJSONString(map).toString());
                } else if (code.trim().equals("验证码:")) {
                    map.put("status", 400);
                    map.put("msg", Constant.CODE);
                    pw.print(JSON.toJSONString(map).toString());
                } else if (currentUser.getLoginName().equals(loginName) && currentUser.getPassword().equals(MD5Util.md5encode(password)) && code.trim().equals(piccode)) {
                    map.put("status", 200);
                    map.put("msg", Constant.LOGIN_SUCCESS);
                    pw.print(JSON.toJSONString(map).toString());
                } else {
                    map.put("status", 400);
                    map.put("msg", Constant.USER_PASSWORD);
                    pw.print(JSON.toJSONString(map).toString());
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            map.put("status", 400);
            map.put("msg", Constant.INTER_EXECTION);
            pw.print(JSON.toJSONString(map).toString());
        } catch (UserException e) {
            e.printStackTrace();
            map.put("status", 400);
            map.put("msg", Constant.INTER_EXECTION);
            pw.print(JSON.toJSONString(map).toString());
        }

    }

    /**
     * 首页
     */
    @RequestMapping("/gotoIndex.do")
    public ModelAndView gotoIndex(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("index");
        return mv;
    }

    /**
     * 登录页面
     */
    @RequestMapping("/toLogin.do")
    public ModelAndView gotoLogin() {
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }


    /**
     * 没有权限
     */
    @RequestMapping("/unauthorized.do")
    public ModelAndView unauthorized() {
        ModelAndView mv = new ModelAndView("404");
        return mv;
    }

    /**
     * 用户退出登陆
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(RedirectAttributes redirectAttributes) {
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        SecurityUtils.getSubject().logout();
        redirectAttributes.addFlashAttribute("message", "您已安全退出");
        return "redirect:/user/toLogin.do";
    }

    /**
     * 根据id查询对象
     *
     * @param request
     * @param response
     * @param
     * @return ResponseEntity
     */
    @RequestMapping("/getUserById.do")
    public String getUserById(HttpServletRequest request, HttpServletResponse response

    ) {
        return null;
    }

}

